<?php

namespace app\api\controller\resell;

use app\api\controller\AuthController;
use app\api\service\GroupOrderService;
use app\api\service\PaymentService;
use app\api\service\ResellOrderService;
use think\exception\ValidateException;

class OrderController extends AuthController
{
    public function save()
    {
        $param = $this->request->param();

        try{
            validate('ResellOrderValidate')->check($param);
        }catch (ValidateException $e){
            return json(['code' => 0,'msg' => $e->getError()]);
        }

        $goods = ResellOrderService::findResellGoods($param['resell_goods_id']);


        if (empty($goods)){
            return json(['code' => 0,'msg' => '商品已下架']);
        }

        $user_id = $this->request->user['user_id'];

        $user = ResellOrderService::getUserInfo($user_id);


        $real_amount = number_format($goods['resell_price'] * $goods['goods_num'],2);

        $order_no = PaymentService::generateOrderNum();

        $out_trade_no = PaymentService::generateOrderNum(10);

        $data = array_merge($user,$param,$goods,[
            'buy_num' => $goods['goods_num'],
            'order_no' => $order_no,
            'out_trade_no' => $out_trade_no,
            'real_amount' => $real_amount,
            'market_price' => $goods['origin_price'],
            'sell_price' => $goods['origin_price'],
            'group_price' => $goods['resell_price'],
        ]);

        /**
         * 保存订单信息
         * */

        $group_order_id = GroupOrderService::saveOrder($data);


        if (empty($group_order_id)){
            return  json(['code' =>0, '下单失败!']);
        }



        $config = PaymentService::findPaymentConfig($param['store_id'],$param['payment_type']);

        if (empty($config)){
            return  json(['code' =>0, 'msg' =>'支付异常!']);
        }

        $payment_data = [
            'config' => $config,
            'trade_method' => $data['payment_type'],
            'out_trade_no' => $out_trade_no,
            'real_amount' => $real_amount,
        ];

        if ($data['payment_type'] == 1){
            $payment_data['notify_url'] = 'https://xiangyule.jcyqkj.cn/api/resell/order/trade/wx/notify';
        }

        if ($data['payment_type'] == 2){
            $payment_data['notify_url'] = 'https://xiangyule.jcyqkj.cn/api/resell/order/trade/ali/notify';
        }


        $prepay_info = PaymentService::createOrder($payment_data);

        if (!empty($prepay_info)){
            return json([
                'code' =>1,
                'data' => [
                    'out_trade_no' => $out_trade_no,
                    'prepay_info' => $prepay_info
                ],
                'msg' => '下单成功!'
            ]);
        }

        return  json(['code' =>0, 'msg' => '下单失败!']);
    }
}